<?php

namespace App\Console\Commands;

use App\Enum\LogsEnum;
use App\Enum\OrderEnum;
use App\Models\LogsModel;
use App\Models\OrderModel;
use Illuminate\Console\Command;

class OrderWarningCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:warning';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'warning order status is abnormal.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 出发异常
        $rows = OrderModel::query()->fromQuery(
            'SELECT id, order_no FROM sxcx_orders WHERE `status` IN (1,2) AND start_time - UNIX_TIMESTAMP()< 1800 AND is_warning='.OrderEnum::ORDER_WARNING_NO
        )->toArray();

        $orderIdWhere = '';
        if( !empty($rows) ){

            $orderIds = array_column($rows,'id');
            $orderIdWhere = ' AND id not in ('.implode(',',$orderIds).')';

            OrderModel::query()->whereIn('id',$orderIds)->update(['is_warning'=>OrderEnum::ORDER_WARNING_BEFORE]);
            // 写入订单日志
            foreach ($rows as $row)
            LogsModel::query()->create([
                'type'      => LogsEnum::LOGS_TYPE_ORDER,
                'ref_id'    => $row['id'],
                'ref_no'    => $row['order_no'],
                'user_id'   => '0',
                'user_type' => LogsEnum::LOGS_USER_TYPE_SYSTEM,
                'username'  => LogsEnum::LOGS_USER_NAME,
                'content'   => '订单预警：标识为出发异常',
            ]);
        }


        // 超时异常
        $rows = OrderModel::query()->fromQuery(
            'SELECT id, order_no  FROM sxcx_orders WHERE `status` NOT IN (4,5) '.$orderIdWhere.' AND start_time + 3600 * 3  < UNIX_TIMESTAMP() AND is_warning='.OrderEnum::ORDER_WARNING_NO
        )->toArray();

        if( !empty($rows) ){
            $orderIds = array_column($rows,'id');
            OrderModel::query()->whereIn('id',$orderIds)->update(['is_warning'=>OrderEnum::ORDER_WARNING_AFTER]);
            // 写入订单日志
            foreach ($rows as $row)
                LogsModel::query()->create([
                    'type'      => LogsEnum::LOGS_TYPE_ORDER,
                    'ref_id'    => $row['id'],
                    'ref_no'    => $row['order_no'],
                    'user_id'   => '0',
                    'user_type' => LogsEnum::LOGS_USER_TYPE_SYSTEM,
                    'username'  => LogsEnum::LOGS_USER_NAME,
                    'content'   => '订单预警：标识为超时异常',
                ]);
        }

        return 0;
    }
}
